package com.ltmonitor.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ltmonitor.dao.IBasicDataDao;
import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.PlatformState;
import com.ltmonitor.service.IBasicDataService;

@Service("basicDataService")
public class BasicDataService extends BaseService<Long, BasicData> implements IBasicDataService {

	@Autowired
	private IBasicDataDao basicDataDao;
	

	/**
	 * 基本信息缓存
	 */
	public static HashMap<String, BasicData> basicDataMap = new HashMap<String, BasicData>();

	/**
	 * 启动时调用Init方法加载所有基础数据到缓存中
	 */
	public void init() {
		String hql = "from BasicData where deleted = ?";
		List result = this.query(hql, false);
		for (Object obj : result) {
			BasicData bd = (BasicData) obj;
			String key = bd.getParent() + "_" + bd.getCode();
			basicDataMap.put(key, bd);
		}
	}

	public void saveOrUpdateAll(List<BasicData> bdList) {
		this.saveOrUpdateAll(bdList);
		for (BasicData bd : bdList) {
			String key = bd.getParent() + "_" + bd.getCode();
			basicDataMap.put(key, bd);
		}
	}

	/**
	 * 保存基础数据并更新缓存
	 * 
	 * @param bd
	 */
	public BasicData saveOrUpdate(BasicData bd) {
		this.baseDao.saveOrUpdate(bd);
		String key = bd.getParent() + "_" + bd.getCode();
		basicDataMap.put(key, bd);
		return bd;
	}

	public List getBaseDataByParentID(Serializable parentID) {
		String queryString = "from BasicData b where b.parent = ? and b.deleted=false order by b.name ASC";
		return this.query(queryString, parentID);

	}

	public BasicData getBasicDataByCode(String code, String parentCode) {
		String key = parentCode + "_" + code;
		BasicData bd = basicDataMap.get(key);
		if (bd == null) {
			bd = (BasicData) this.find(
					"from BasicData a where a.code = ? and a.parent = ? order by a.sn",
					new Object[] { code, parentCode });
			basicDataMap.put(key, bd);
		}

		return bd;
	}

	public List<BasicData> getBasicDataByParentCode(String parentCode) {

		String queryString = "from BasicData b where b.parent = ?  and b.deleted=false order by b.sn ASC";

		List<BasicData> result = this.query(queryString, parentCode);
		return result;
	}
	
	
	/**
	 * 根据信息类型获得要发布的信息列表
	 * @param inforType
	 * @return
	 */
	public List<BasicData> getInformationByType(String inforType)
	{
		String hql = "from BasicData where parent = ? and code = ? and deleted = ?";
		
		List<BasicData> result = this.query(hql, new Object[]{"Information", inforType, false});
		return result;
	}
	
	
	/**
	 * 获得平台的各个服务器的连接状态
	 */
	public PlatformState getPlatformState()
	{
		PlatformState ps =  (PlatformState)this.query("from PlatformState order by entityId");
		if(ps == null)
		{
			ps = new PlatformState();
			//this.saveOrUpdate(ps);
		}
		return ps;
	}
	
	

}
